import { ElMessage } from 'element-plus'
import { mainStore } from '../../../store/mainStore'
import { _uploadFile, _sendUploadUrl, _setUploadUrl } from '/src/api/FileTransfer/main.js'

/**
 *  点击上传区域时触发文件输入框
 */
export const uploadClick = () => {
  const fileInput = document.getElementById('file-input')
  fileInput.click()
}

/**
 *  文件输入框改变时触发上传
 */
export const uploadChange = (event) => {
  handleFiles(event.target.files)
}

/**
 *  拖拽区域事件处理 阻止打开默认文件
 */
export const dragover = (event) => {
  event.preventDefault()
}

/**
 *  拖拽区域事件处理 离开拖拽区域
 */
export const dragleave = (event) => {}

/**
 *  拖拽区域事件处理 完成拖拽
 */
export const drop = (event) => {
  event.preventDefault()
  // 获取拖拽的文件列表
  const files = event.dataTransfer.files
  // 处理文件
  handleFiles(files)
}

/**
 *  提交上传
 */
export const submitUpload = async (error) => {
  if (error) return
  const store = mainStore()

  try {
    // 处理数据
    // 先调用路径接口
    const { path } = store.uploadFile

    if (!path) {
      // 调接口给予默认上传路径
      const res = await _sendUploadUrl()
      if (res.data?.code == 200) store.uploadFile.path = res.data.data['upload-folder']
    } else {
      // 设置文件上传路径
      await _setUploadUrl({ 'upload-folder': store.uploadFile.path })
    }

    // 处理数据成fordata
    const formdata = new FormData()
    formdata.set('file', store.uploadFile.body)

    const res = await _uploadFile(formdata)

    if (res.data?.code == 200) {
      ElMessage.success('上传成功')
      // 保存历史输入
      let res = JSON.parse(localStorage.getItem('historyInputs'))
      if (res) {
        res.push(store.uploadFile.path)
        res = [...new Set(res)]
        localStorage.setItem('historyInputs', JSON.stringify(res))
      } else {
        localStorage.setItem('historyInputs', JSON.stringify([store.uploadFile.path]))
      }

      store.uploadFile = {
        name: null,
        size: null,
        body: null,
        path: null,
      }
      document.getElementById('file-input').value = null
    }
  } catch (error) {
    console.log(error)

    ElMessage.error('上传失败')
  }
}

/**
 *  文件处理 只允许上传文件
 */
const handleFiles = (files) => {
  if (files.length != 1) return ElMessage.error('只允许上传一个文件')
  const file = files[0]
  if (isFile(file)) return ElMessage.error('只能上传文件')
  saveFile(file)
}

/**
 *  判断是否为文件
 */
const isFile = (file) => {
  return file.size === 0 && !file.name.includes('.')
}

/**
 *  劫持文件
 */
const saveFile = (file) => {
  const store = mainStore()
  store.uploadFile.name = file.name
  store.size = file.size
  store.uploadFile.body = file
}

/**
 *  检测一个对象中是否存在某一项是 undefined
 * 或者是否缺少某个键值对
 * @param {object} obj 要检测的对象
 * @param {array} expectedKeys 要检测的键值对
 */

const checkObjectProperties = (obj, expectedKeys) => {
  for (let key of expectedKeys) {
    if (obj[key] == undefined) {
      return false
    }
  }
  return true
}
